package com.jh.jingfei.login.ui;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.jh.jingfei.MyApplication;
import com.jh.jingfei.R;
import com.jh.jingfei.main.MainActivity;
import com.jh.jingfei.models.Account;
import com.jh.jingfei.repositories.AccountRepository;
import com.jh.jingfei.ui.LoadingDialogFragment;
import com.jh.jingfei.utils.RegexUtils;
import com.strongloop.android.loopback.AccessToken;
import com.strongloop.android.loopback.RestAdapter;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * @author lxb
 *
 * A simple {@link Fragment} subclass.
 * Use the {@link LoginFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LoginFragment extends SupportFragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private TextView goRegisterTv;

    private TextInputEditText usernameEt;
    private TextInputEditText passwordEt;

    private boolean unOk = false;
    private boolean pwdOk = false;

    private Button loginBtn;

    public LoginFragment() {
        Log.i("Login : ", "LoginFragment");
    }

    public static LoginFragment newInstance(String param1, String param2) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_login, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        usernameEt = view.findViewById(R.id.username_et);
        passwordEt = view.findViewById(R.id.password_et);

        goRegisterTv = view.findViewById(R.id.go_register_tv);
        loginBtn = view.findViewById(R.id.login_btn);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        goRegisterTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start(RegisterFragment.newInstance("", ""));
            }
        });

        usernameEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(!TextUtils.isEmpty(s) && RegexUtils.isEmail(s)) {
                    unOk = true;
                } else {
                    unOk = false;
                }
                toggleLoginBtn();
            }
        });

        passwordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)) {
                    pwdOk = true;
                } else {
                    pwdOk = false;
                }
                toggleLoginBtn();
            }
        });

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = usernameEt.getText().toString();
                String pwd = passwordEt.getText().toString();
                if (!RegexUtils.isEmail(email)) {
                    usernameEt.setError("邮箱错误");
                } else {
                    loginAction(email, pwd);
                }
            }
        });
    }

    private void toggleLoginBtn() {
        if ( unOk && pwdOk) {
            loginBtn.setEnabled(true);
        } else {
            loginBtn.setEnabled(false);
        }
    }

    private void loginAction(String email, String pwd) {
        //
//        Intent intent = new Intent(getContext(), MainActivity.class);
//        startActivity(intent);
//        _mActivity.finish();

        final LoadingDialogFragment loadingDialogFragment = LoadingDialogFragment.newInstance("", "");
        loadingDialogFragment.show(getFragmentManager(), LoadingDialogFragment.TAG);

        Log.i("LOGIN", "=====");
        RestAdapter restAdapter = new RestAdapter(getContext(), getString(R.string.base_url));
        AccountRepository up = restAdapter.createRepository(AccountRepository.class);

        up.loginUser(email, pwd, new com.strongloop.android.loopback.UserRepository.LoginCallback<Account>() {
            @Override
            public void onSuccess(AccessToken token, Account currentUser) {
                loadingDialogFragment.dismiss();

                MyApplication app = (MyApplication) LoginFragment.this.getActivity().getApplication();
                app.setAccessToken((String) token.getId());
                app.setAccount(currentUser);
                app.setUserId((int)currentUser.getId());
                Log.d("Login Token", ((String) token.getId()).toLowerCase());
                Log.d("Login Account", currentUser.toString());


                Intent intent = new Intent(getContext(), MainActivity.class);
                startActivity(intent);
                _mActivity.finish();
            }

            @Override
            public void onError(Throwable t) {
                loadingDialogFragment.dismiss();
                Log.i("Login Throwable", t.toString());
            }
        });
    }
}
